package iziswing.composant;


import iziswing.SwingXml;

import java.awt.Container;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;

import metier.ContexteComposant;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import exception.ComposantException;
import exception.DisplayException;
import exception.SwingXmlException;

@SuppressWarnings("serial")
public class JButton extends javax.swing.JButton implements ActionListener {

	private static Logger mLogger = Logger.getLogger(JButton.class.getName());

	private Container mFenetre;
	private ContexteComposant mContexte;
	
	public JButton(Container aObject, ContexteComposant aContexte) throws ComposantException {
		super();
		mLogger.debug("Initialisation du JButton - Action :"+aContexte.getAction());
		mContexte = aContexte;
		mFenetre = aObject;
		setText(aContexte.getTitre());
		
		Point lPoint = ComposantTools.getSize(mContexte);
		setBounds(mContexte.getX(),mContexte.getY(),lPoint.y,lPoint.x);
		
		addActionListener(this);
		mFenetre.add(this);
	}

	@Override
	public void actionPerformed(ActionEvent aArg0) {
		if (mFenetre != null && StringUtils.isNotBlank(mContexte.getAction())) {
			try {
				SwingXml.action(mFenetre, mContexte.getAction());
			} catch (SwingXmlException e) {
				(new DisplayException(e)).display();
			}
		}
	}
	@SuppressWarnings("unchecked")
	public static Object newInstance(Container aFenetre, ContexteComposant aContexte,Object aComposantOut) throws ComposantException{
		try {
			Class<JComponent> lComposant = (Class<JComponent>) Class.forName(aContexte.getModeleClasse().getClasse());
			if(lComposant.equals(JButton.class)){
				aComposantOut = new JButton(aFenetre,aContexte); 
			}
		} catch (ClassNotFoundException e) {
			mLogger.debug(e);
		}
		return aComposantOut;
	}
}
